<template>
  <div class="rolePage">
    <div class="add_role" v-if="hasPerm('user:add')">
      <el-button type="primary" size="mini" @click="showCreate">添加角色</el-button>
    </div>
    <el-table :data="list" fit border class="userTable"   >
      <el-table-column align="center" label="#" width="80px" >
          <template slot-scope="scope">
            {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" prop="roleName" width="150"></el-table-column>
      <el-table-column align="center" label="角色描述" prop="description" width="150"></el-table-column>
      <el-table-column label="状态"  align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.available">
            正常
          </el-tag>
          <el-tag v-else type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="菜单&权限" width="350">
        <template slot-scope="scope">
           <el-tag v-if="scope.row.roleName === '何志超'" type="success">全部</el-tag>
           <div v-else>
             <div  v-for="(menu,index) in scope.row.menus" :key="index"  style="text-align: left;line-height: 41px;">
               <span style="width: 100px;display: inline-block;text-align: right;padding-right: 6px ">{{menu.menuName}}</span>
               <el-tag v-for="perm in menu.permissions" :key="perm.permissionName" v-text="perm.permissionName"
                      style="margin-right: 3px;"
                      type="primary"></el-tag>
             </div>
           </div>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="管理"  v-if="hasPerm('role:upa') || hasPerm('role:delete') ">
        <template slot-scope="scope">
          <div v-if="scope.row.roleName !== '管理员'">
            <el-button  type="text" icon="el-icon-edit" class="btn-sz" v-if="hasPerm('role:upa')"  @click="showUpdate(scope.row)">修改</el-button>
            <!-- <el-button  type="text" icon="el-icon-delete" class="red btn-sz"  v-if="hasPerm('role:delete')" @click="removeRole(scope.$index)">删除</el-button> -->
          <el-button
          v-if="scope.row.available && hasPerm('role:delete')"
            type="text"
            icon="el-icon-delete"
            class="red btn-sz"
            @click="changeStatu(scope.row,'禁用')"
            >禁用</el-button
          >
          <el-button
          v-if="!scope.row.available && hasPerm('role:delete')"
            type="text"
            icon="el-icon-delete"
            class="red btn-sz"
            @click="changeStatu(scope.row,'启用')"
            >启用</el-button
          >
          </div>
          <div v-else>
            <el-button type="success" icon="edit" @click="changePassword" >重置密码</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="queryInfo.pagenum"
          :page-size="queryInfo.pagesize"
          :total="pageTotal"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 弹出对话框区域 -->
    <el-dialog v-dialogDrag width="820px" @close=blankUser custom-class="userDialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="tempRole" label-position="left" label-width="100px"  style='width: 780px; margin-left:20px; height:400px;'>
        <el-form-item label="角色名称" required>
          <el-input type="text" v-model="tempRole.roleName" style="width: 250px;">
          </el-input>
        </el-form-item>
        <el-form-item label="描述" required>
          <el-input type="text" v-model="tempRole.description" style="width: 250px;">
          </el-input>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-switch
          v-model="userSwitch"
          active-text="启用"
          inactive-text="禁用"
          >
         </el-switch>
        </el-form-item>
        <el-form-item label="菜单&权限" required class="userForm">
          <div v-for="(item,_index) in allPermission" :key="item.menuName" class="allBox">
            <div class="firstBox">
              <div class="firstItem">
                <el-tag>
                  {{item.menuName}}
                </el-tag>
              </div>
            </div>
            <div class="secondBox">
             <div v-for="(menu,__index) in item.permissions" :key="menu.menuName" class="secondItem">
              <div class="secondItem_buttonBox">
                <el-button :type="isMenuNone(_index,__index)?'':(isMenuAll(_index,__index)?'success':'primary')" @click="checkAll(_index,__index)" size="mini" style="width:150px;">{{menu.menuName}}</el-button>
              </div>
              <div class="threeBox">
                <el-checkbox-group v-model="tempRole.permissions">
                  <el-checkbox @change="checkRequired(cItem,_index,__index)" v-for="cItem in menu.permissions" :key="cItem.id" :label="cItem.id">
                    <div :class="{requiredPerm:cItem.requiredPerm===1}">{{cItem.permissionName.slice(-2)}}</div>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
             </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="createRole">创 建</el-button>
        <el-button type="primary" v-else @click="updateRole">修 改</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="重置密码"
      :visible.sync="passwordDialogVisible"
      width="400px"
      >
      <el-form :inline="true" :model="passwordForm" style="margin-left:20px;">
        <el-form-item label="密码" required="">
          <el-input v-model="passwordForm.password" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changePasswordDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { commonGetList, commonRoleAdd, commonRoleUpa, commonRoleUpaAvailable, commonRoleFindById } from "../../../service/common";
export default {
  data() {
    return {
      userSwitch:false,
      pageTotal:0,
      queryInfo: {
        pagenum: 1,
        pagesize: 6,
      },
      list: [], //渲染tabel
      allPermission: [],
      listLoading: true,
      dialogFormVisible:false,
      passwordDialogVisible:false,
      passwordForm:{
        password:''
      },
      tempRole:{
        roleName: '',
        id: '',
        description:'',
        permissions: [],
      },
      textMap: {
        update: '编辑',
        create: '新建角色'
      },
      dialogStatus:'create'
    };
  },
  created() {
    this.getList();
    // this.getAllPermisson();
    console.log(this.$store.getters.permissions)
  },
  methods: {
   // 分页导航
    handlePageChange(val) {
      this.$set(this.queryInfo, 'pagenum', val);
      this.getList()
    },
    //查询列表
    async getList() {
      try {
      const res = await commonGetList(this.queryInfo);
      console.log(res, "权限res");
      this.listLoading = false;
      this.list = res.sysUsers.records;
      this.pageTotal = res.sysUsers.total
      this.allPermission = res.permissions
      } catch (error) {
        console.log(error, "权限接口异常");
      }
    },
    //查询所有权限
    async getAllPermisson() {
      const res = await commonGetAllPermissont();
      console.log(res, "获取所有权限res");
      this.allPermission = res.list;
      },
    // 重置密码
    changePassword() {
      this.passwordDialogVisible = true
    },
    changePasswordDialog() {
      this.passwordDialogVisible = false
    },
    //显示角色新增对话框
    showCreate() {
     this.tempRole.roleName = '';
     this.tempRole.id = '';
     this.tempRole.description = ''
     this.tempRole.permissions = [];
     this.dialogStatus = "create"
     this.dialogFormVisible = true
    },
    // 编辑角色
    async showUpdate(item) {
      console.log(item,'编辑角色item')
      const res = await commonRoleFindById({id:item.id})
      console.log('res:编辑角色res ', res);
      if (res.code == '200') {
        this.tempRole.permissions = res.data.permissions.map(Number)
      }
      if (item.available) {
        this.userSwitch = true
      }else {
        this.userSwitch = false
      }

      this.tempRole.roleName = item.roleName;
      this.tempRole.description = item.description;
      this.tempRole.id = item.id;
      console.log(this.allPermission,'递归this.allPermission')
      console.log(this.tempRole.permissions,'递归this.tempRole.permissions')
      this.dialogStatus = "update"
      this.dialogFormVisible = true
    },
    // 递归遍历出所有permissionId
    getTreeId(node,arr) {
      if (!node.menus && !node.permissions) {
        return arr.push(node.permissionId)
      }else {
        if (node.menus) {
          node.menus.forEach(item => {
          this.getTreeId(item,arr)
        })
        }else if (node.permissions) {
        node.permissions.forEach(item => {
          this.getTreeId(item,arr)
        })
        }
      }
    },
    // 判断是否一个都没选
    isMenuNone(_index,__index) {
      return this.allPermission[_index].permissions[__index].permissions.every(item => this.tempRole.permissions.indexOf(item.id) == -1)
    },

    // 判断是否全选
    isMenuAll(_index,__index) {
     return this.allPermission[_index].permissions[__index].permissions.every(item => this.tempRole.permissions.indexOf(item.id) > -1)
    },

    // 全选区域

    // 点击全选按钮
    checkAll(_index,__index) {
      if(this.isMenuAll(_index,__index)) {
        this.noPerm(_index,__index);
      }else {
        this.allPerm(_index,__index)
      }
    },
    // 全部选中
    allPerm(_index,__index) {
       this.allPermission[_index].permissions[__index].permissions.forEach(item => {
        this.addUnique(item.id, this.tempRole.permissions)
      })
    },
    // 取消选中
    noPerm(_index,__index) { 
      this.allPermission[_index].permissions[__index].permissions.forEach(item => {
        let idIndex = this.tempRole.permissions.indexOf(item.id)
        if (idIndex > -1) {
          this.tempRole.permissions.splice(idIndex,1)
        }
      })
    },

    // 单选区域

    // 点击单选
    checkRequired(perm,_index,__index) {
      if(this.tempRole.permissions.indexOf(perm.id) > -1) {
        this.makeReuqiredPermissionChecked(_index,__index);
      }else if (perm.requiredPerm == 1) {
        // 如果点的是列表必选项
        this.noPerm(_index,__index);
      }
    },
    // 判断必选是否勾上
    makeReuqiredPermissionChecked(_index,__index) {
      this.allPermission[_index].permissions[__index].permissions.forEach(item => {
        if (item.requiredPerm == 1) {
          this.addUnique(item.id, this.tempRole.permissions)
        }
      })
    },
    // 将必选打钩
    addUnique(val, arr) {
      //数组内防重复地添加元素
      let _index = arr.indexOf(val);
      if (_index < 0) {
        arr.push(val);
      }
    },
    //添加新角色
    async createRole() {
      
      console.log(this.tempRole,'this.tempRole')
      return
      if (!this.checkroleNameUnique()) {
        return;
      }
      if (!this.checkPermissionNum()) {
        return;
      }
      if (this.userSwitch) {
        this.tempRole.available = 1
      }else {
        this.tempRole.available = 0
      }
      // let param = {
      //   available: 1,
      //   description: "test1",
      //   permissions: '1',
      //   id: "",
      //   roleName: "test1",
      // }
      // const res = await commonRoleAdd(param)
      const res = await commonRoleAdd(this.tempRole)
      console.log(res,'添加角色res')
        this.getList();
        this.dialogFormVisible = false
    },
    // 修改角色
    async updateRole() {
      if (this.userSwitch) {
        this.tempRole.available = 1
      }else {
        this.tempRole.available = 0
      }
      if (!this.checkroleNameUnique(this.tempRole.id)) {
        return;
      }
      if (!this.checkPermissionNum()) {
        return;
      }
       const res =  await commonRoleUpa(this.tempRole)
       if (res.code == 200) {
         this.$message.success(res.msg)
       }else{
         this.$message.error(res.msg)
       }
       console.log('res修改角色 ', res);
        this.getList();
        this.dialogFormVisible = false
    },
    // 删除角色
      removeRole($index) {
      let _that = this;
      this.$confirm('确定删除此角色?', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      }).then(async () => {
        let role = _that.list[$index];
        await commonDeleteRole({
          id: role.id
        })
         _that.getList()
      })
    },
            // 删除操作
    changeStatu(row,state) {
      let available 
      if (row.available) {
        available = 0
      }else {
        available = 1
      }
        // 二次确认删除
        this.$confirm(`确定要${state}吗？`, '提示', {
            type: 'warning'
        })
        .then(async () => {
           let param = {
            id:row.id,
            available: available
           }
          const res = await commonRoleUpaAvailable(param)
            console.log('res:状态改变返回 ', res);
            this.$message.success(`${state}成功`);
            this.getList()
        })
        .catch(() => {});
    },
    // 置空弹出框
    blankUser() {
    },
    //校验名称重复
    checkroleNameUnique(id) {
      let roleName = this.tempRole.roleName;
      if (!roleName) {
        this.$message.error("请填写角色名称");
        return false;
      }
      let roles = this.list;
      let result = true;
      for (let j = 0; j < roles.length; j++) {
        if (roles[j].roleName === roleName && (!id || roles[j].id !== id  )) {
          this.$message.error("角色名称已存在");
          result = false;
          break;
        }
      }
      return result;
    },
    //校验至少有一种权限
    checkPermissionNum() {
      if (this.tempRole.permissions.length === 0) {
        this.$message.error("请至少选择一种权限");
        return false;
      }
      return true;
    },  
  },
  computed: {
    ...mapGetters(["userId"]),
  }
};
</script>

<style lang="less" scoped>
.rolePage {
  width: 100%;
  height: 100%;
  padding-top: 15px;
  padding-left: 20px;
  background-color: #fff;

   .pagination {
   margin: 20px 0;
   text-align: right;
 }

  .userForm {
    height: 260px;
    overflow-y: auto;
  }

  .userTable {
    margin-top: 10px;
    overflow: auto;
  }

  // .add_role {
  //   width: 100%;
  //   line-height: 70px;
  // }
.allBox {
  display: flex;
  align-items: center;
  border-top: 1px solid #eee;
  &:last-child {
    border-bottom: 1px solid #eee;
  }
  .firstBox {
    width: 100px;
    text-align: center;
   .firstItem {
    display: inline;
    width: 100px;
   }
  }

  .secondBox {
    width: 100%;
    text-align: left;
    flex-direction: column;
   .secondItem {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
    .secondItem_buttonBox {
      width: 150px;
      margin-right: 10px;
    }
   } 
}
  .requiredPerm {
    color: #ff0e13;
  }
}
}
</style>